package com.wr.springbootadmin.service;

import com.alibaba.fastjson.JSON;
import com.wr.springbootadmin.conponet.ConfigPrepertiesComponet;
import com.wr.springbootadmin.pojo.*;
import com.wr.springbootadmin.service.impl.DoWorkServiceImpl;
import com.wr.springbootadmin.utils.UploadImg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xuxuebing
 * @create 2021/8/17 15:05
 * @target
 */
@Slf4j
@Service
public class DoHistoryWorkService {
    
    @Autowired
    private HikHistoryApkService hikHistoryApkService;

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public void wenZhouShiJu() throws Exception{

        List<String> collect = DoWorkServiceImpl.wenzhouDataPojoList.stream().map(WenzhouDataPojo::getIndexCode).collect(Collectors.toList());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int day= 20;
        Date startdate= df.parse("2021-08-23 22:00:00");
        long initTime= 0l;
        for (int i = 0; i < 1; i++) {
            for (int j = 0; j < 2; j++) {
                long time = startdate.getTime();
                
                initTime = i*24*60*60*1000+ j*60*60*1000;
                time+=initTime ;
                
                Date star = new Date(time);
                Date end = new Date(time+60*60*1000);

                String startTimeStr = null;
                String endTimeStr = null;
                startTimeStr = df.format(star);
                endTimeStr = df.format(end);
                
                log.info(startTimeStr);
                log.info(endTimeStr);

                List<PicPojo> picPojoList = hikHistoryApkService.getImgUrlByIndexCodeList(collect, "21656980", "v0cdY8IQMoOVpairzN89", "61.164.105.28:6443", startTimeStr, endTimeStr);

                HashSet<PicPojo> PicPojoSet = new HashSet<>(picPojoList);


                log.info(JSON.toJSONString(picPojoList));
                List<CangNanPojo> cangNanImgDatalist1 = new ArrayList<>();
                PicPojoSet.forEach(picPojo -> {
                    Date parse = null;
                    try {
                        parse = sdf2.parse(picPojo.getCaptureTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String format1 = sdf.format(parse);

                    CangNanPojo cangNanPojo = new CangNanPojo();
                    cangNanPojo.setGmtCollect(format1);
                    String captureUrl = picPojo.getCaptureUrl();
                    String newUrl = captureUrl.replace("http://10.33.158.145:8081", "https://61.164.105.28:6443");
                    cangNanPojo.setImgUrl(newUrl);
                    cangNanPojo.setName(picPojo.getCameraName());
                    if (picPojo.getCameraName().equals("乐清市钟前一级水电站")) {
                        CangNanPojo cangNan = new CangNanPojo();
                        cangNan.setGmtCollect(format1);
                        cangNan.setImgUrl(newUrl);
                        cangNan.setName("乐清市钟前二级水电站");
                        cangNan.setVideoCode("3303821002");
                        cangNanImgDatalist1.add(cangNan);
                    }

                    if (picPojo.getCameraName().equals("乐清市十八玍水电站")) {
                        CangNanPojo cangNan = new CangNanPojo();
                        cangNan.setGmtCollect(format1);
                        cangNan.setImgUrl(newUrl);
                        cangNan.setName("乐清市岭脚水电站");
                        cangNan.setVideoCode("3303821018");
                        cangNanImgDatalist1.add(cangNan);
                    }

                    cangNanPojo.setVideoCode(picPojo.getCameraIndexCode());
                    cangNanImgDatalist1.add(cangNanPojo);
                });

                DoWorkServiceImpl.wenzhouDataPojoList.forEach(wenzhouDataPojo -> {
                    cangNanImgDatalist1.forEach(cangNanPojo -> {
                        if (wenzhouDataPojo.getIndexCode().trim().equals(cangNanPojo.getVideoCode())) {
                            cangNanPojo.setVideoCode(wenzhouDataPojo.getDataCode());
                        }
                    });
                });
                log.info("抓到图片：" + cangNanImgDatalist1.size());
                log.info(JSON.toJSONString(cangNanImgDatalist1));

                pushImgShiju(cangNanImgDatalist1);


            }
            
        }
        
        
        
        
    }

    @Autowired
    private ConfigPrepertiesComponet configPrepertiesComponet;

    public void pushImgShiju(List<CangNanPojo> cangNanImgDatalist) throws Exception {
        List<StaticImgDataPojo> list = new ArrayList<>();
        Map<String, String> stringStringMap = jsonToMap("hyst_config.json");
        for (int i = 0; i < cangNanImgDatalist.size(); i++) {
            CangNanPojo cangNanPojo = cangNanImgDatalist.get(i);
            String uploadToLocalPath = uploadToShiju(cangNanPojo.getImgUrl(), cangNanPojo.getName(), configPrepertiesComponet.getCangnanImgPath());
            if (!StringUtils.isEmpty(uploadToLocalPath)) {
                toPushImg(uploadToLocalPath, list, cangNanPojo, stringStringMap);
            }
        }
        realTimeDataOfStaticPictures(list, configPrepertiesComponet.getWenzhouUserCode(), configPrepertiesComponet.getWenzhouPassWord());

    }
    
    @Autowired
    private RestTemplate restTemplate;

    public void realTimeDataOfStaticPictures(List<StaticImgDataPojo> list, String userCode, String passWord) {

        if (list.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            RealTimeDataPojo realTimeDataPojo = new RealTimeDataPojo();
            realTimeDataPojo.setList(list);
            realTimeDataPojo.setPassWord(passWord);
            realTimeDataPojo.setUserCode(userCode);
            realTimeDataPojo.setRowCount(list.size());
            realTimeDataPojo.setTableCode("videoRecords");
            map.put("rmap", realTimeDataPojo);
            log.info(JSON.toJSONString(map));
            HashMap map2 = restTemplate.postForObject(configPrepertiesComponet.getDockingUrlPre(), map, HashMap.class);
            log.info(userCode + ":" + map2.get("message"));
        }
    }


    public void toPushImg(String uploadToLocalPath, List<StaticImgDataPojo> list, CangNanPojo cangNanPojo, Map<String, String> stringStringMap) {

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        // 设置请求的格式类型
        headers.setContentType(type);
        FileSystemResource fileSystemResource = new FileSystemResource(uploadToLocalPath);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("userCode", configPrepertiesComponet.getWenzhouUserCode());
        form.add("passWord", configPrepertiesComponet.getWenzhouPassWord());
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        try {
            StaticImgDataPojo staticImgDataPojo = new StaticImgDataPojo();
            Map<String, Object> map = new HashMap<>();
            Thread.sleep(300);
            ResponseEntity<HashMap> hashMapResponseEntity = restTemplate.postForEntity(configPrepertiesComponet.getDockingImgUpload(), files, HashMap.class);
            log.info("推送完成");
            System.out.println(hashMapResponseEntity.getBody());
            HashMap bodyMap = hashMapResponseEntity.getBody();
            Integer status = (Integer) bodyMap.get("status");
            if (status.equals(0)) {
                HashMap messageMap = (HashMap) bodyMap.get("message");
                Integer fileId = (Integer) messageMap.get("fileId");
                staticImgDataPojo.setFileId(fileId);
                staticImgDataPojo.setUserCode(configPrepertiesComponet.getWenzhouUserCode());
                staticImgDataPojo.setHourTime(cangNanPojo.getGmtCollect());
                staticImgDataPojo.setVideoCode(cangNanPojo.getVideoCode());
                list.add(staticImgDataPojo);
            }
            String gmtCollect = cangNanPojo.getGmtCollect();
            Date parse = sdf3.parse(gmtCollect);
            map.put("PIC_INFO", imgPaeseBase64Str(uploadToLocalPath));
            map.put("REC_TIME", sdf3.format(parse));
            map.put("HYST_CODE", cangNanPojo.getVideoCode());
            map.put("WAIN_NUM", "01");
            String token = stringStringMap.get(cangNanPojo.getVideoCode());
            if (token != null) {
                log.info("开始保存图片：" + JSON.toJSONString(cangNanPojo));
                savaImg(cangNanPojo.getVideoCode(), map, token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            File file = new File(uploadToLocalPath);
            file.delete();
        }

    }

    public String imgPaeseBase64Str(String imgUrl) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgUrl);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);

    }


    public void savaImg(String videoCode, Map<String, Object> map, String token) throws IOException {
        String url = "http://61.164.105.24:38060/htwaterAPI/ReportStaticPictureInfo";
        HttpHeaders headers = new HttpHeaders();
        headers.add("AuthorizationKey", videoCode);
        headers.add("AuthorizationToken", token);
        headers.add("Content-Type", "application/json");

        Map<String, Object> parem = new HashMap<>();
        ArrayList<Map> arrayList = new ArrayList<>();
        arrayList.add(map);
        parem.put("DATA", arrayList);
        String body = JSON.toJSONString(parem);
        HttpEntity<String> entity = new HttpEntity(body, headers);
        String result = restTemplate.postForObject(url, entity, String.class);
        log.info(result);

    }


    public Map<String, String> jsonToMap(String jsonLocalFileName) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource(jsonLocalFileName);
        InputStream is = classPathResource.getInputStream();
        String result = IOUtils.toString(is, StandardCharsets.UTF_8);
        List<JsonPojo> jsonPojos = JSON.parseArray(result, JsonPojo.class);
        Map<String, String> map = jsonPojos.stream().collect(Collectors.toMap(JsonPojo::getVedioCode, JsonPojo::getToken));
        return map;

    }

    public String uploadToShiju(String imgUrl, String cameraName, String localDirPath) throws NoSuchAlgorithmException, IOException, KeyManagementException {
        long l = System.currentTimeMillis();
        String fileName = l + "-" + cameraName + ".jpg";
        String localPath = UploadImg.downloadBShiJu(imgUrl, fileName, localDirPath);
        return localPath;
    }


}
